const express = require("express")
const {
    User
} = require('../mod/user')
const register = express.Router() //创建路由

const Mail = require("../mod/mail.js")
var {
    setCrypto
} = require('../mod/crypto.js')

register.post("/", async (req, res) => {
    // console.log(req.body)
    let {
        password
    } = req.body
// console.log(req.body)
    //具体使用，注意在登陆时也需要对传入的数据进行一次加密，再比较
    password = setCrypto(password)
    // console.log(password)
    req.body.password=password
    // console.log(req.body)
    let time1 = Date.now()
    let obj = JSON.parse(process.env.code)

    // console.log(time1 - obj.time)
    // console.log()
    let olduser = await User.findOne({
        username: req.body.username
    })
    if (req.body.yzmval != obj.code1) {
        return res.status(201).send("验证码错误")
    }
    if (time1 - obj.time >= 1000 * 60 * 5) {

        return res.status(202).send("验证码已经失效")

    }
    if (olduser) {
        return res.status(203).send({
            message: "用户已经存在"
        })
    }
    let newuser = await new User(req.body).save()
    // process.env.code=null
    res.status(200).send({
        data: newuser
    })
})


register.get("/postmail", async (req, res) => {
    let {
        email
    } = req.query
    let codetime = parseInt(Math.random() * 10000)
    let data1 = await Mail.sendmail(email, codetime)
    let time = Date.now()
    process.env.code = JSON.stringify({
        code1: codetime,
        time: time
    })
    res.status(200).send({
        message: "发送成功"
    })
})



module.exports = register